<template>
  <div class="signatureBox">
    <div class="text">
      <p class="p1">请在线进行手写签名</p>
      <p class="p2">您的签名将由系统生成在申请文书中，视同对申请文书的电子签名。</p>
    </div>
    <div class="canvasBox" ref="canvasHW">
      <canvas
        @touchstart='touchStart'
        @touchmove='touchMove'
        @touchend='touchEnd'
        @mousedown="mouseDown"
        @mousemove="mouseMove"
        @mouseup="mouseUp"
        ref="canvasF">
      </canvas>
    </div>
    <div class="btnBox">
      <div class="bottom">
        <Button type="warning" @click="overwrite">重写</Button>
        <Button type="primary" @click="commit">确定</Button>
      </div>
    </div>
  </div>
</template>
<script>
  import request from '../../utils/request'
  export default {
    data() {
      return {
        points: [],
        startX: 0,
        startY: 0,
        moveY: 0,
        moveX: 0,
        endY: 0,
        endX: 0,

        w: null,
        h: null,
        imgData: '',
        isDown: false,
        canvasBoard: null,
        canvasContext: null,
        currentSignatureData: ''
      }
    },
    beforeRouteEnter(to, from, next) {
      if (from.name === 'BusinessConfirmList') {
        alert('您已签字成功，无法返回至签字页面')
        history.pushState(null, null, from.fullPath)
      } else {
        next()
      }
    },
    methods: {
      mouseDown(ev) {
        ev = ev || event
        ev.preventDefault()
        // console.log(ev)

        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }

        // console.log(obj)
        this.startX = obj.x
        this.startY = obj.y
        this.canvasContext.beginPath()
        this.canvasContext.moveTo(this.startX, this.startY)
        this.canvasContext.lineTo(obj.x, obj.y)
        this.canvasContext.stroke()
        this.canvasContext.closePath()
        this.points.push(obj)
        this.isDown = true
      },

      // Mobile event -- Touch start
      touchStart(ev) {
        ev = ev || event
        ev.preventDefault()
        if (ev.touches.length === 1) {
          let obj = {
            x: ev.targetTouches[0].clientX - this.w * (15 / 100),
            y: ev.targetTouches[0].clientY - this.h / 20
          }
          // console.log(ev)

          this.startX = obj.x
          this.startY = obj.y
          this.canvasContext.beginPath()
          this.canvasContext.moveTo(this.startX, this.startY)
          this.canvasContext.lineTo(obj.x, obj.y)
          this.canvasContext.stroke()
          this.canvasContext.closePath()
          this.points.push(obj)
        }
      },

      // Mobile -- Mouse move
      mouseMove(ev) {
        ev = ev || event
        ev.preventDefault()
        if (this.isDown) {
          let obj = {
            x: ev.offsetX,
            y: ev.offsetY
          }

          this.moveY = obj.y
          this.moveX = obj.x
          this.canvasContext.beginPath()
          this.canvasContext.moveTo(this.startX, this.startY)
          this.canvasContext.lineTo(obj.x, obj.y)
          this.canvasContext.stroke()
          this.canvasContext.closePath()
          this.startY = obj.y
          this.startX = obj.x
          this.points.push(obj)
        }
      },

      // Mobile event -- Touch move
      touchMove(ev) {
        ev = ev || event
        ev.preventDefault()
        if (ev.touches.length === 1) {
          let obj = {
            x: ev.targetTouches[0].clientX - this.w * (15 / 100),
            y: ev.targetTouches[0].clientY - this.h / 20
          }

          this.moveY = obj.y
          this.moveX = obj.x
          this.canvasContext.beginPath()
          this.canvasContext.moveTo(this.startX, this.startY)
          this.canvasContext.lineTo(obj.x, obj.y)
          this.canvasContext.stroke()
          this.canvasContext.closePath()
          this.startY = obj.y
          this.startX = obj.x
          this.points.push(obj)
        }
      },

      // Computer event -- Mouse up
      mouseUp(ev) {
        ev = ev || event
        ev.preventDefault()

        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }

        this.canvasContext.beginPath()
        this.canvasContext.moveTo(this.startX, this.startY)
        this.canvasContext.lineTo(obj.x, obj.y)
        this.canvasContext.stroke()
        this.canvasContext.closePath()
        this.points.push(obj)
        this.points.push({ x: -1, y: -1 })
        this.isDown = false
      },

      // Mobile event TouchEnd
      touchEnd(ev) {
        ev = ev || event
        ev.preventDefault()
        // console.log(ev)
        if (ev.touches.length === 1) {
          let obj = {
            x: ev.targetTouches[0].clientX - this.w * (15 / 100),
            y: ev.targetTouches[0].clientY - this.h / 20
          }

          this.canvasContext.beginPath()
          this.canvasContext.moveTo(this.startX, this.startY)
          this.canvasContext.lineTo(obj.x, obj.y)
          this.canvasContext.stroke()
          this.canvasContext.closePath()
          this.points.push(obj)
          this.points.push({ x: -1, y: -1 })
        }
      },

      // Over write
      overwrite() {
        this.canvasContext.clearRect(
          0,
          0,
          this.$refs.canvasF.width,
          this.$refs.canvasF.height
        )
        this.points = []
      },

      // Commit
      commit() {
        this.currentSignatureData = this.$refs.canvasF.toDataURL('image/png')
        this.rotateBase64Img(this.currentSignatureData, -90)
        this.$Modal.confirm({
          title: '签字确认',
          content: '<p>请确认填报内容符合您真实意愿，签字朝向是否与页面文字朝向一致，签字为本人签署并清晰准确？</p>',
          onOk: () => {
            let confirm = JSON.parse(sessionStorage.getItem('confirm'))
            request.post('/outer/file/confirm/uploadSign.do', {
              file: sessionStorage.getItem('imgSrc').substring(22),
              gid: confirm.gid,
              confirmid: confirm.confirmid
            }).then(response => {
                if (response.data.result === 'error') {
                  this.$ErrorAlert(response.data.message)
                  return null
                }
                this.$SuccessAlert('签字确认成功，返回至业务确认列表页')
                this.$router.push({ name: 'BusinessConfirmList' })
              })
          }
        })
      },
      rotateBase64Img(src, edg) {
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')

        var imgW // 图片宽度
        var imgH // 图片高度
        var size // canvas初始大小

        if (edg % 90 !== 0) {
          console.error('旋转角度必须是90的倍数!')
          return '旋转角度必须是90的倍数!'
        }
        edg < 0 && (edg = edg % 360 + 360)
        const quadrant = (edg / 90) % 4 // 旋转象限
        const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 } // 裁剪坐标

        var image = new Image()
        image.crossOrigin = 'anonymous'
        image.src = src

        image.onload = function() {
          imgW = image.width
          imgH = image.height
          size = imgW > imgH ? imgW : imgH

          canvas.width = size * 2
          canvas.height = size * 2
          switch (quadrant) {
            case 0:
              cutCoor.sx = size
              cutCoor.sy = size
              cutCoor.ex = size + imgW
              cutCoor.ey = size + imgH
              break
            case 1:
              cutCoor.sx = size - imgH
              cutCoor.sy = size
              cutCoor.ex = size
              cutCoor.ey = size + imgW
              break
            case 2:
              cutCoor.sx = size - imgW
              cutCoor.sy = size - imgH
              cutCoor.ex = size
              cutCoor.ey = size
              break
            case 3:
              cutCoor.sx = size
              cutCoor.sy = size - imgW
              cutCoor.ex = size + imgH
              cutCoor.ey = size + imgW
              break
          }

          ctx.translate(size, size)
          ctx.rotate(edg * Math.PI / 180)
          ctx.drawImage(image, 0, 0)

          var imgData = ctx.getImageData(
            cutCoor.sx,
            cutCoor.sy,
            cutCoor.ex,
            cutCoor.ey
          )
          if (quadrant % 2 === 0) {
            canvas.width = imgW
            canvas.height = imgH
          } else {
            canvas.width = imgH
            canvas.height = imgW
          }
          ctx.putImageData(imgData, 0, 0)
          sessionStorage.setItem('imgSrc', canvas.toDataURL())
        }
      }
    },
    beforeMount(height) {
      this.h =
        document.documentElement.clientHeight || document.body.clientHeight
      this.w = document.documentElement.clientWidth || document.body.clientWidth
    },
    mounted() {
      this.canvasBoard = this.$refs.canvasF
      this.canvasBoard.height = this.$refs.canvasHW.offsetHeight
      this.canvasBoard.width = this.$refs.canvasHW.offsetWidth
      this.canvasContext = this.canvasBoard.getContext('2d')
      this.canvasContext.beginPath()
      this.canvasContext.lineWidth = 5
      this.canvasContext.stroke()
    }
  }
</script>
<style>
  .signatureBox {
    width: 100%;
    height: 100%;
    background: #808080;
    padding: 5% 15%;
    position: relative;
    overflow: hidden;
  }
  .canvasBox {
    width: 100%;
    height: 90%;
  }
  .canvasBox canvas {
    /* display: block; */
    background: #fff;
  }
  .bottom {
    padding-top: 5%;
    display: flex;
    justify-content: space-around;
  }
  .bottom button {
    width: 45%;
    padding-top: 0.36rem;
    padding-bottom: 0.36rem;
    font-size: 0.57rem;
  }
  .signatureBox .text {
    font-size: 0.5rem;
    transform-origin: left top;
    width: 100vh;
    text-align: center;
    position: absolute;
    top: 0;
    left: 97%;
    transform: rotate(90deg);
  }
  .signatureBox .text .p1 {
    color: yellow;
  }
  .signatureBox .text .p2 {
    color: #fff;
  }
</style>
